package cn.ty.znsz.common.interceptor;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.redis.Redis;

import cn.ty.znsz.common.utils.CommonUtils;

public class RequestInterceptor implements Interceptor {

	public void intercept(Invocation inv) {
		Controller controller = inv.getController();

		HttpServletRequest request = controller.getRequest();
		String url = request.getRequestURL().toString() + "?" + request.getQueryString();
		String httpurl = PropKit.get("httpurl");
		//后端通过cookie验证
		String sessionId = controller.getCookie("jznsz");
		System.out.println(sessionId);
		// 解决跨域请求问题
		controller.getResponse().addHeader("Access-Control-Allow-Origin", "*");
	
		// 1、判断是否从本网站访问系统
		if (url.startsWith(httpurl)) {
			if(sessionId !=null) {
				if(Redis.use().exists(sessionId)==false) {
					//缓存已经失效,删除原来cookie
					controller.removeCookie("jznsz");
					controller.renderHtml(CommonUtils.renderHtmlText(Ret.fail("登陆信息已失效，请重新登陆")));
					return;
				}else {
					inv.invoke();
				}
			}else {
				controller.renderHtml(CommonUtils.renderHtmlText(Ret.fail("登陆信息已失效，请重新登陆")));
				return;
			}
		} else {//报错处理,返回登录页面
			controller.renderHtml(CommonUtils.renderHtmlText(Ret.fail("登陆信息已失效，请重新登陆")));
			return;
		}
	}

}
